
package com.chongchong.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chongchong.core.secure.utils.SecureUtil;
import com.chongchong.core.tool.api.R;
import com.chongchong.core.tool.utils.StringUtil;
import com.chongchong.system.dto.EmailTemplateDTO;
import com.chongchong.system.entity.EmailTemplate;
import com.chongchong.system.mapper.EmailTemplateMapper;
import com.chongchong.system.service.IEmailTemplateService;
import com.chongchong.system.vo.EmailTemplateVO;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *  服务实现类
 *
 * @author en
 * @since 2022-07-21
 */
@Service
public class EmailTemplateTemplateServiceImpl extends ServiceImpl<EmailTemplateMapper, EmailTemplate> implements IEmailTemplateService {

	@Override
	public IPage<EmailTemplateVO> selectSysEmailTemplatePage(IPage<EmailTemplateVO> page, EmailTemplateDTO sysEmailTemplate) {
		return page.setRecords(baseMapper.selectSysEmailTemplatePage(page, sysEmailTemplate));
	}

	@Override
	public List<EmailTemplateVO> listAll(String mouldName) {
		return baseMapper.listAll(mouldName);
	}

	@Override
	public String createEmailMouldNo() {
		String maxMouldNo = baseMapper.findMaxMouldNo();
		if (!StringUtil.hasText(maxMouldNo)){
			return "EMAIL_0001";
		}else {
			int no = Integer.parseInt(maxMouldNo.split("\\_")[1]);
			no++;
			return "EMAIL_"+(no<10?"000"+no:no<100?"00"+no:no<1000?"0"+no:no);
		}
	}

	@Override
	public R saveData(EmailTemplate entity){
		QueryWrapper<EmailTemplate> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mould_name",entity.getMouldName());
		if (baseMapper.selectCount(queryWrapper)>0){
			return R.fail("模板名称（"+entity.getMouldName()+"）已存在");
		}
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setCreateUserId(SecureUtil.getUserId());
		entity.setUpdateUserId(SecureUtil.getUserId());
		entity.setIsDeleted(0);
		return R.status(save(entity));
	}

	@Override
	public R updateData(EmailTemplate entity) {
		QueryWrapper<EmailTemplate> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mould_name",entity.getMouldName());
		queryWrapper.ne("id",entity.getId());
		if (baseMapper.selectCount(queryWrapper)>0){
			return R.fail("模板名称（"+entity.getMouldName()+"）已存在");
		}
		entity.setUpdateTime(new Date());
		entity.setUpdateUserId(SecureUtil.getUserId());
		return R.status(updateById(entity));
	}
}
